package com.lingnan.blog.mapper;

import com.lingnan.blog.entity.Article;
import com.lingnan.blog.provider.ArticleProvider;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface ArticleMapper {


    /**
     * 查询所有文章
     *
     * @return
     */
    @Select("select * from article")
    List<Article> selectAll();


    /**
     * 根据id查询作者及其发布的文章
     *
     * @param id 文章id
     * @return Article
     */
    @Select("select * from article where id = #{id} ")
    Article selectById(Integer id);


    /**
     * 根据用户id查询当前用户的文章(UserMapper引用一对多)
     *
     * @param uid 用户id
     * @return List<Articles>
     */
    @Select("select * from article where u_id = #{uid} ")
    List<Article> selectByUid(Integer uid);

    /**
     * 查询所有笔记文章
     *
     * @return List<Articles>
     */
    @Select("select * from article where tag = '面试'")
    List<Article> selectInterviewArticle();

    /**
     * 更新文章的浏览总数
     *
     * @param id
     * @return
     */
    @Update("update article set views = views+1 where id = #{id} ")
    int updateView(@Param("id") int id);

    /**
     * 根据id查询文章浏览总数
     *
     * @param id
     * @return
     */
    @Select("select views from article where id = #{id} ")
    int selectByViews(Integer id);

    /**
     * 根据id查询文章收藏总数
     *
     * @param id
     * @return
     */
    @Select("select collects from article where id = #{id} ")
    Integer findByCollects(Integer id);

    /**
     * 更新文章收藏总数
     *
     * @param id
     * @param collects
     * @return
     */
    @Update("update article set collects = #{collects} where id = #{id}  ")
    Integer updateCollects(Integer id, Integer collects);


    /**
     * 根据标签名字查询所有文章
     *
     * @param tag
     * @return
     */
    @Select("select * from `article` where tag = #{tag} ")
    List<Article> selectByTag(String tag);

    /**
     * 保存文章
     *
     * @param article
     */
    @InsertProvider(type = ArticleProvider.class, method = "insert")
    //插入成功后返回主键
    @Options(useGeneratedKeys = true, keyProperty = "id")
    void insert(Article article);

    /**
     * 更新文章
     *
     * @param article
     */
    @UpdateProvider(type = ArticleProvider.class, method = "update")
    void update(Article article);

    @Update("update article set comments = comments+1 where id = #{id}")
    void updateComments(Integer id);
}